package main

import (
	lib "im/libs"
	"im/model"
	protos "im/proto"
	"net"
)

var users map[string]string = map[string]string{
	"admin": "123",
	"abc":   "123",
	"def":   "123",
}

var uids map[string]uint64 = map[string]uint64{
	"admin": 123,
	"abc":   125,
	"def":   210,
}
var t *model.Token

func do_auth(conn net.Conn, req *protos.AppReq) {
	r := &protos.AppRsp{Command: protos.Command_AUTH}
	addr := conn.RemoteAddr().String()
	r.Token, _ = t.Gen(uids[req.Username], addr)
	rsp, _ := lib.EncodeAppRsp(r)
	conn.Write(rsp)
}

func appHandle(t *(lib.Task)) {

	//t.Client.Write([]byte("Hello"))
	///fmt.Println("from", t.Client.RemoteAddr())
	defer t.Client.Close()
	buffer := make([]byte, 1024)
	length := make([]byte, 4)
	for {
		_, err := t.Client.Read(length)
		if err != nil {
			break
		}
		l := lib.GetMsgLength(length)
		//fmt.Printf("length<===%v\n",l)
		data := make([]byte, l)
		total := int32(0)
		for {
			n, err := t.Client.Read(buffer)
			if err != nil {
				return
			}
			for i := int32(0); i < int32(n); i += 1 {
				data[total+i] = buffer[i]
			}
			total += int32(n)
			if total >= l {
				break
			}
		}
		req, _ := lib.DecodeAppReq(data)
		switch req.Command {
		case protos.Command_AUTH:
			if users[req.Username] == req.Password {
				do_auth(t.Client, req)
			} else {
				r := &protos.AppRsp{Command: protos.Command_ERROR}
				rsp, _ := lib.EncodeAppRsp(r)
				t.Client.Write(rsp)
			}
		default:
			r := &protos.AppRsp{Command: protos.Command_ERROR}
			rsp, _ := lib.EncodeAppRsp(r)
			t.Client.Write(rsp)
		}

	}

}

func main() {
	redis, err := lib.NewRedisConfig("./config")
	if err != nil {
		panic("redis config load failed.")
	}
	if r, e := redis.Servers["user"]; e {
		t, err = model.NewToken(&r)
		if err != nil {
			panic("redis config connect failed.")
		}
		s, _ := lib.NewServer("127.0.0.1", 1001, 10, appHandle)
		s.Start()
	} else {
		panic("redis config load failed.")
	}

}
